<template>
  <ul class="pagination" v-if="pageAll > 1">
    <li v-if="showPrev"><a href="javascript:" @click="prevClick">&laquo;</a></li>
    <li v-for="index in indexes" :class="{ 'active': cur == index}">
      <a @click="btnClick(index)" href="javascript:">{{ index }}</a>
    </li>
    <li v-if="showLast"><a @click="nextClick" href="javascript:">&raquo;</a></li>
    <li><a>共<i>{{pageAll}}</i>页</a></li>
  </ul>
</template>
<script>
  import {sckr} from  '@/lib/sckr'
  import jsonp from 'jsonp'
  export default{
    data () {
      return {
        cur: 0 // 当前页vue2.0中要求不能改变props里的值的大小
      }
    },
    props: ['curPage', 'pageAll', 'perPage'],
    created () {
      this.cur = this.curPage;
    },
    computed: {
      indexes () {
        let list = [];
        // 计算左右页码
        let mid = parseInt(this.perPage / 2) // 中间值
        let left = Math.max(this.cur - mid, 1)
        let right = Math.max(this.cur + this.perPage - mid - 1, this.perPage)
        if (right > this.pageAll) { right = this.pageAll }
        while (left <= right) {
          list.push(left)
          left++
        }
        return list;
      },
      showLast () {
        return this.cur != this.pageAll
      },
      showPrev () {
        return this.cur != 1;
      }
    },
    methods: {
      // 页码点击事件
      btnClick (index) {
        if (index != this.cur) {
          this.cur = index;
          this.$emit('change-page', index);
        }
      },
      nextClick () {
        if (this.cur < this.pageAll) {
          this.cur++;
          this.$emit('change-page', this.cur)
        }
      },
      prevClick () {
        if (this.cur > 0) {
          this.cur--;
          this.$emit('change-page', this.cur)
        }
      }
    },
    watch: {
      curPage (val, oldVal) {
        this.$emit('change-page', val);
      }
    }
  }
</script>
<style scoped>
  .pagination {  display: inline-block;  vertical-align: middle;  margin: 20px auto;  }
  .pagination li {  margin-left: 2px;  margin-right: 2px;  display: inline-block;  }
  .pagination li.disabled span {  color: #c5c5c5;  }
  .pagination li a, .pagination li span {  display: inline-block;  vertical-align: middle;  padding: 0 15px;  border: 1px solid #e2e2e2;
    height: 28px;  line-height: 28px;  margin: 0 -1px 5px 0;  background-color: #fff;  color: #333;  font-size: 14px;  }
  .pagination li.active a, .pagination li a:hover {  background-color: #1570d6;  color: #fff;  }
</style>
